package com.banmoon.prototype;

import cn.hutool.core.io.IoUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Estanciero implements Cloneable, Serializable {

    private String name;

    private List<Sheep> sheepList;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Estanciero estanciero = (Estanciero) super.clone();
        if(estanciero.getSheepList()!=null){
            ArrayList<Sheep> list = new ArrayList<>();
            estanciero.getSheepList().forEach(sheep -> list.add(sheep));
            estanciero.setSheepList(list);
        }
        return estanciero;
    }

    public Estanciero cloneBySerializable(){
        // 创建输出流
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        // 创建输入流
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            // 序列化当前对象
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            Estanciero copyEstanciero = (Estanciero) ois.readObject();

            return copyEstanciero;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭流
            IoUtil.close(bos);
            IoUtil.close(oos);
            IoUtil.close(bis);
            IoUtil.close(ois);
        }


    }

}
